package kni.hoid;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

public class VufindSearchService implements SearchService {

	// "author:shakespeare+title:dancer+"
	private String searchServiceURL = "http://mobile.mzk.cz/api/search?q=searchTerms&start=startIndex&rows=count";

	static Map<Item.Type, String> enumToType = new HashMap<Item.Type, String>();
	static {
		enumToType.put(Item.Type.ALL_FIELDS, null);
		enumToType.put(Item.Type.AUTHOR, "author");
		enumToType.put(Item.Type.ISBN, "isbn");
		enumToType.put(Item.Type.TITLE, "title");
	}

	public List<Book> search(List<Item> what) {
		String searchString = "";
		for (Item item : what) {
			String prefix = enumToType.get(item.getType());
			if (prefix != null) {
				searchString += prefix + ":" + "\"" + URLEncoder.encode(item.getWhat()) + "\""
						+ "+";
			} else {
				searchString += item.getWhat() + "+";
			}
		}
		String url = searchServiceURL;
		url = url.replaceAll("searchTerms", searchString);
		url = url.replaceAll("startIndex", "0");
		url = url.replaceAll("count", "20");
		List<Book> books = new ArrayList<Book>();
		/*
		Book bookDebug = new Book();
		bookDebug.setTitle(url);
		books.add(bookDebug);
		*/
		try {
			JSONObject json = HttpConnector.httpGetRequest(url);
			JSONArray results = json.getJSONArray("docs");
			for (int i = 0; i!= results.length(); i++) {
				JSONObject result = results.getJSONObject(i);
				Book book = new Book();
				book.setTitle(result.getString("title"));
				book.setAuthor(result.getString("author"));
				book.setIsbn(result.getString("isbn"));
				book.setPublishDate(result.getString("publishDate"));
				books.add(book);
			}
		} catch (Exception ex) {
			/* 
			bookDebug = new Book();
			bookDebug.setTitle("chyba!!!");
			books.add(bookDebug);
			*/
			ex.printStackTrace();
		}
		return books;
	}

}
